package com.fgs.common.other;

import android.content.Context;
import android.text.TextUtils;

import com.fgs.common.CommonModel;
import com.fgs.common.CommonResponse;
import com.fgs.common.api.CommonApiService;
import com.fgs.common.api.CommonConfig;
import com.fgs.common.entity.region.AreaInfo;
import com.fgs.common.entity.region.CityInfo;
import com.fgs.common.entity.region.ProvinceInfo;
import com.fgs.common.entity.region.RegionInfo;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.CommonUtil;
import com.fgs.common.utils.LogUtil;
import com.google.gson.reflect.TypeToken;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.resource.ResourceUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fgs
 * @date 2020/3/31
 * @description
 **/
public class RegionData {

    //Nationwide(全国)  Province（全省） City(全市) Normal
    public static final int TYPE_NORMAL = 0;
    public static final int TYPE_NATIONWIDE = 1;
    public static final int TYPE_PROVINCE = 2;
    public static final int TYPE_CITY = 3;

    private List<ProvinceInfo> provinceItems = new ArrayList<>();
    private List<List<CityInfo>> cityItems = new ArrayList<>();
    private List<List<List<AreaInfo>>> areaItems = new ArrayList<>();
    private List<ProvinceInfo> provinceInfos;
    private int defaultProvince;
    private int defaultCity;
    private int defaultArea;

    public void setDefaultProvinceString(String defaultProvinceString) {
        this.defaultProvinceString = defaultProvinceString;
    }

    public void setDefaultCityString(String defaultCityString) {
        this.defaultCityString = defaultCityString;
    }

    public void setDefaultAreaString(String defaultAreaString) {
        this.defaultAreaString = defaultAreaString;
    }

    private String defaultProvinceString;
    private String defaultCityString;
    private String defaultAreaString;

    private RegionData() {
    }

    public static RegionData getInstance() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static RegionData instance = new RegionData();
    }

    public void loadRegionInfo() {
        new CommonModel().subscribe(CommonUtil.getContext(), CommonConfig.getInstance().create(CommonApiService.class).regionInfo(), new ObserverResponseListener<CommonResponse<List<RegionInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<RegionInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    List<RegionInfo> regionInfoList = commonResponse.getData();
                    init(regionInfoList);
                } else {
                    LogUtil.print(commonResponse.getMsg());
                    initData();
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                LogUtil.print(e.message);
                initData();
            }
        });
    }

    public void initData() {
        String JsonData = ResourceUtils.readStringFromAssert("region.json");
        List<RegionInfo> regionInfoList = JsonUtil.fromJson(JsonData, new TypeToken<List<RegionInfo>>() {
        }.getType());
        init(regionInfoList);
    }

    public void init(List<RegionInfo> regionInfoList) {
        if (regionInfoList == null) return;
        int size = regionInfoList.size();
        RegionInfo regionInfo;
        ProvinceInfo provinceInfo = null;
        CityInfo cityInfo = null;
        List<ProvinceInfo> provinceInfoList = new ArrayList<>();
        List<CityInfo> cityList;
        String parentCode = "";
        for (int i = 0; i < size; i++) {
            regionInfo = regionInfoList.get(i);
            if (regionInfo.level.equals("1")) {
                parentCode = regionInfo.code;
                provinceInfo = new ProvinceInfo();
                provinceInfo.name = regionInfo.province;
                provinceInfo.code = regionInfo.code;
                provinceInfo.cityList = new ArrayList<>();

                provinceInfoList.add(provinceInfo);
            } else if (regionInfo.level.equals("2")) {
                cityInfo = new CityInfo();
                cityInfo.code = regionInfo.code;
                if (TextUtils.isEmpty(regionInfo.city)) {
                    cityInfo.name = regionInfo.label;
                } else {
                    cityInfo.name = regionInfo.city;
                }
                if (regionInfo.parentcode.equals(parentCode)) {
                    provinceInfo.cityList.add(cityInfo);

                } else {
                    cityList = new ArrayList<>();
                    cityList.add(cityInfo);
                    provinceInfo.cityList.addAll(cityList);

                }
                parentCode = regionInfo.code;
                cityInfo.areaList = new ArrayList<>();

            } else if (regionInfo.level.equals("3")) {
                if (regionInfo.parentcode.equals(parentCode)) {
                    AreaInfo area = new AreaInfo();
                    if (TextUtils.isEmpty(regionInfo.county)) {

                        area.name = regionInfo.city;
                    } else {
                        area.name = regionInfo.county;

                    }
                    area.code = regionInfo.code;
                    cityInfo.areaList.add(area);
                }
            }

        }
        provinceInfos = provinceInfoList;
//        LogUtil.print(JsonUtil.toJson(provinceInfoList));
    }

    public boolean loadProvinceData(int loadType) { //加载省份数据

        if (provinceInfos == null) {
            return false;
        }


        List<ProvinceInfo> tempProvinceList = new ArrayList<>();
        ProvinceInfo info;
        CityInfo cityInfo;
        AreaInfo areaInfo;

        if (loadType == TYPE_NATIONWIDE) {
            info = new ProvinceInfo();
            info.name = "全国";
            tempProvinceList.add(info);

        }
        int size = provinceInfos.size();
        for (int i = 0; i < size; i++) {

            info = new ProvinceInfo();
            info.name = provinceInfos.get(i).name;
            info.code = provinceInfos.get(i).code;
            info.cityList = new ArrayList<>();
            info.cityList.addAll(provinceInfos.get(i).cityList);
            tempProvinceList.add(info);

            if (loadType == TYPE_PROVINCE) {
                cityInfo = new CityInfo();
                cityInfo.name = "全省";
                info.cityList.add(0, cityInfo);
            }

        }

        provinceItems.clear();
        cityItems.clear();
        areaItems.clear();
        //遍历省份（第一级）

//        LogUtil.print(JsonUtil.toJson(tempProvinceList));

        for (ProvinceInfo provinceInfo : tempProvinceList) {


            provinceItems.add(provinceInfo);
            //该省的城市列表（第二级）
            List<CityInfo> cityList = new ArrayList<>();
            //该省的所有地区列表（第三级）
            List<List<AreaInfo>> areaList = new ArrayList<>();

            if (provinceInfo.cityList == null) continue;

            for (CityInfo city : provinceInfo.cityList) {
                //添加城市
                cityInfo = new CityInfo();
                cityInfo.name = city.name;
                cityInfo.code = city.code;

                //该城市的所有地区列表
                List<AreaInfo> cityAreaList = new ArrayList<>();

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (city.areaList == null || city.areaList.size() == 0) {

                    if (loadType == TYPE_NATIONWIDE | loadType == TYPE_PROVINCE | loadType == TYPE_CITY) {
                        if (city.name.equals("全省")) {
                            areaInfo = new AreaInfo();
                            areaInfo.name = "";
                            cityAreaList.add(areaInfo);
                        } else {
                            areaInfo = new AreaInfo();
                            areaInfo.name = "全市";
                            cityAreaList.add(areaInfo);
                        }
                    } else {
                        areaInfo = new AreaInfo();
                        areaInfo.name = "";
                        cityAreaList.add(areaInfo);
                    }

                } else {
//                    if (loadType == TYPE_NATIONWIDE | loadType == TYPE_PROVINCE | loadType == TYPE_CITY) {
//                        areaInfo = new AreaInfo();
//                        areaInfo.name = "全市";
//                        cityAreaList.add(areaInfo);
//                    }
                    cityAreaList.addAll(city.areaList);
                }
                //添加该省所有地区数据
                areaList.add(cityAreaList);
                cityInfo.areaList = cityAreaList;
                cityList.add(cityInfo);
            }

            /**
             * 添加城市数据
             */
            cityItems.add(cityList);

            /**
             * 添加地区数据
             */
            areaItems.add(areaList);

        }
//        loadDefaultData(isShowAll);

        return true;
    }

    /**
     * @return 获取默认城市的索引
     */
//    public void loadDefaultData(boolean isShowAll) {
//        ProvinceInfo provinceInfo;
//        List<ProvinceInfo.City> cities;
//        ProvinceInfo.City city;
//        List<String> ares;
//        for (int i = 0; i < provinceItems.size(); i++) {
//            provinceInfo = provinceItems.get(i);
//            if (!TextUtils.isEmpty(defaultProvinceString) && defaultProvinceString.equals(provinceInfo.getName())) {
//                defaultProvince = i;
//                cities = provinceInfo.getCityList();
//                for (int j = 0; j < cities.size(); j++) {
//                    city = cities.get(j);
//                    if (!TextUtils.isEmpty(defaultCityString) && defaultCityString.equals(city.getName())) {
//                        defaultCity = j;
//                        ares = city.getArea();
//                        for (int k = 0; k < ares.size(); k++) {
//                            if (!TextUtils.isEmpty(defaultAreaString) && defaultAreaString.equals(ares.get(k))) {
//                                defaultArea = k;
//                                break;
//                            }
//                        }
//                        break;
//                    }
//                }
//                break;
//            }
//        }
//    }
    public int getDefaultProvince() {
        return defaultProvince;
    }

    public int getDefaultCity() {
        return defaultCity;
    }

    public int getDefaultArea() {
        return defaultArea;
    }

    public ProvinceInfo getProvinceInfo(int options) {

        return provinceItems.get(options);

    }

    public CityInfo getCityInfo(int options1, int options2) {
        return cityItems.get(options1).get(options2);
    }

    public AreaInfo getAreaInfo(int options1, int options2, int options3) {
        return areaItems.get(options1).get(options2).get(options3);
    }


    public List<ProvinceInfo> getProvinceItems() {
        return provinceItems;
    }

    public List<List<CityInfo>> getCityItems() {
        return cityItems;
    }

    public List<List<List<AreaInfo>>> getAreaItems() {
        return areaItems;
    }
}
